//
//  LYPersonalListView.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/31.
//

import UIKit

enum PersonalListCellType: String, RawRepresentable {
    case `enum` = "senior"
    case txt = "leukid"
    case citySelect = "mechanon"
}

class LYPersonalListView: UIView {
    
    var didClickListClourse: ((Megaloplanesque) -> Void)?
    var didTextFieldChanged: ((Megaloplanesque) -> Void)?
    
    var dataSource: [Megaloplanesque] = [] {
        didSet {
            self.tableView.reloadData()
        }
    }
    
    lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.register(LYPersonalListCell.self, forCellReuseIdentifier: "LYPersonalListCell")
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 120
        tableView.backgroundColor = .clear
        tableView.shouldIgnoreScrollingAdjustment = true
        tableView.shouldRestoreScrollViewContentOffset = true
        return tableView
    }()
 
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInitSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func commonInitSubviews() {
        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
}

extension LYPersonalListView: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "LYPersonalListCell", for: indexPath) as! LYPersonalListCell
        cell.configure(with: dataSource[indexPath.row])
        cell.didClickButtonClourse = { [weak self] m in
            guard let self = self else { return }
            self.didClickListClourse?(m)
            tableView.endEditing(true)
        }
        cell.didTextFieldChanged = self.didTextFieldChanged
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        tableView.endEditing(true)
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let aspectRatio = 91.0 / 346.0
        let imageHeight = (SCREEN_WIDTH - LYPersonalListCell.leftRMargin * 2) * aspectRatio
        return imageHeight + LYPersonalListCell.top
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        tableView.endEditing(true)
    }
}


